/**
 * Copyright (c) 2015-2017, Henry Yang 杨勇 (gismail@foxmail.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mapfinal.server.auth.model;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Record;
import com.lambkit.Lambkit;
import com.lambkit.common.service.ServiceKit;
import com.lambkit.db.sql.column.Column;
import com.mapfinal.server.MapfinalServer;
import com.mapfinal.server.MapfinalServerConfig;
import com.mapfinal.server.auth.RoleUserService;
import com.mapfinal.server.auth.service.impl.RoleUserServiceImpl;

/**
 * @author yangyong 
 * @website: www.lambkit.com
 * @email: gismail@foxmail.com
 * @date 2020-09-23
 * @version 1.0
 * @since 1.0
 */
public class RoleUser extends RoleUserBase<RoleUser> {

	private static final long serialVersionUID = 1L;
	
	public static RoleUserService service() {
		return ServiceKit.inject(RoleUserService.class, RoleUserServiceImpl.class);
	}
	
	public static RoleUserCriteria sql() {
		return new RoleUserCriteria();
	}
	
	public static RoleUserCriteria sql(Column column) {
		RoleUserCriteria that = new RoleUserCriteria();
		that.add(column);
        return that;
    }

	public RoleUser() {
		MapfinalServerConfig config = Lambkit.config(MapfinalServerConfig.class);
		String dbconfig = config.getDbConfig();
		if(StrKit.notBlank(dbconfig)) {
			this.use(dbconfig);
		}
	}

	public boolean save(Object role_id, Object user_id) {
		Record userRole = new Record().set("user_id", user_id).set("role_id", role_id);
		return MapfinalServer.db().save("mf_role_user", "user_id, role_id", userRole);
	}
	
	public boolean update(Object role_id, Object new_role_id, Object user_id) {
		if(role_id==null || new_role_id==null || user_id==null) return false;
		if(role_id.toString().equals(new_role_id.toString())) return true;
		RoleUser m = findFirst("select * from mf_role_user where user_id=? and role_id=?", user_id, role_id);
		if(m!=null) {
			m.set("role_id", new_role_id);
		}
		return m.update();
	}
}
